<?php
/**
 * @version $Id: tb.php 244 2008-03-11 21:11:21Z mikhail.miguel $
 * @author  Takeshi Kuriyama <kuri@keynext.co.jp>
 */

$mytrustdirname = basename( dirname( __FILE__ ) ) ;
$mytrustdirpath = dirname( __FILE__ ) ;

require_once dirname(dirname(__FILE__)).'/lib/trackback/trackback.php';

// check if user has perm
if(!$currentUser->blog_perm()) {
    exit(d3blog_responseError("Thanks, but you don't have permission to access this entry", 1));
}

$entry_handler =& $myModule->getHandler('entry');
$tb_handler =& $myModule->getHandler('trackback');

// get id from PATH_INFO
$id = TrackbackService::getId();
if(TrackbackService::isError($id) || empty($id)) {
    exit(d3blog_responseError('Invalid trackback key', 1));
}
$id = str_replace("\0", "", $id);  

switch( $_SERVER['REQUEST_METHOD'] ) {

case 'GET':
default:
    if($myModule->getConfig('trackback_ticket')) {	
        // get blog ID when a ticket url system is on.
        if(preg_match("/^[0-9a-z]+$/", $id) && strlen($id) == 12) {
            // get bid
            $obj =& $tb_handler->getByTbkey($id);
            if(!$obj) {
                exit(d3blog_responseError('No such key id found. Re-get trackback ticket.', 1));
            }    	
            $bid = $obj->getVar('bid');
        } else {
        	$bid = intval($id);
        }
    } else {
    	$bid = intval($id);
    }

    $entry =& $entry_handler->getEntry($bid, false);
    if(!$entry) {
        exit(d3blog_responseError('No such blog entry found', 1));
    }

    if( isset($_GET['__mode']) && $_GET['__mode'] == "rss" ) {
        $trackback = new  TrackbackService();

        $trackback->_data['title'] = $entry->getVar('title', 'n');
        $trackback->_data['excerpt'] = $entry->pingExcerpt();
        $trackback->_data['url'] = sprintf('%s/modules/%s/details.php?bid=%d', XOOPS_URL, $mydirname, $entry->bid());
        $trackback->_data['encoding'] = 'UTF-8';
        $trackback->_data['language'] = _LANGCODE;

        // gather received trackback data
        $tbs = $tb_handler->getTrackback($entry->bid(), null, true);
        $rss = array();
        foreach($tbs['inbound'] as $tb) {
            $rss[] = array(
                'title' => $tb->getVar('title', 'n'),
                'url' => $tb->getVar('url', 'n'),
                'excerpt' => $tb->getVar('excerpt', 'n')
                );
        }
        $result = $trackback->getPingList($rss);
        echo $result;

    } else {
        header('Location:' . sprintf('%s/modules/%s/details.php?bid=%d', XOOPS_URL, $mydirname, $bid )) ;
        exit;
    }
    break;

case 'POST':
    if($myModule->getConfig('trackback_ticket')) {
        if(!preg_match("/^[0-9a-z]+$/", $id) || strlen($id)!=12) {
            exit(d3blog_responseError('Invalid trackback key', 1));
        }
        // get bid
        $obj =& $tb_handler->getByTbkey($id);
        if(!$obj) {
            exit(d3blog_responseError('No such key id found. Re-get trackback id.', 1));
        }
        $bid = $obj->getVar('bid');
    } else {
        $bid = intval($id);
    }

    $entry =& $entry_handler->getEntry($bid);
    if(!$entry) {
        exit(d3blog_responseError('No such blog entry found', 1));
    }
    
    $trackback = new TrackbackService();

    $trackback->_data['id'] = $bid;
    $result = $trackback->receive();

    if($trackback->isError($result)) {
        exit(d3blog_responseError($result->getMessage(), 1));
    }

    // check if the trackback data sent to again
    $criteria = new criteriaCompo(new criteria('direction', 2));
    $criteria->add(new criteria('bid', $bid));
    $criteria->add(new criteria('url', addslashes($trackback->_data['url'])));
    $objs =& $tb_handler->getObjects($criteria);
    if(count($objs)) {
        exit(d3blog_responseError('Thanks again, you sent this trackback before', 1));
    }

    // SPAM check
    $check_items = $myModule->getConfig('spam_check');
    if(is_array($check_items) && !in_array('n', $check_items)) {
        if(XOOPS_USE_MULTIBYTES == 1 && function_exists('mb_strlen') && in_array('l', $check_items) && $myModule->getConfig('regex_pattern')) {
            $options['sources'] = array($myModule->getConfig('regex_pattern'));
            $options['elements'] = array('title', 'blog_name', 'excerpt');
            $options['minlength'] = intval($myModule->getConfig('Character'));
            $result = $trackback->createSpamCheck('Character', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        if(in_array('f', $check_items)) {
            $options['sources'] = array(
                XOOPS_URL."/modules/$mydirname/details.php?bid=$bid",
                XOOPS_URL."/modules/$mydirname/tb.php/$bid"
            );
            $options['elements'] = array('url');
            $result = $trackback->createSpamCheck('Reference', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        if(in_array('w', $check_items) && $myModule->getConfig('wordlist')) {
            $options['sources'] = preg_split("/[\s]+/", $myModule->getConfig('wordlist'));
            $options['elements'] = array('title', 'blog_name', 'excerpt');
            $options['comparefunc'] = array('SpamCheck_Wordlist', '_stripos');
            $result = $trackback->createSpamCheck('Wordlist', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        if(in_array('r', $check_items) && $myModule->getConfig('regex')) {
            $options['sources'] = '('.implode('|', preg_split("/[\s]+/", $myModule->getConfig('regex'))).')';
            $options['elements'] = array('title', 'blog_name', 'excerpt', 'url');
            $result = $trackback->createSpamCheck('Regex', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        if(in_array('d', $check_items) && $myModule->getConfig('dnsbl')) {
            $options['sources'] = preg_split("/[\s]+/", $myModule->getConfig('dnsbl'));
            $result = $trackback->createSpamCheck('DNSBL', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        if(in_array('s', $check_items) && $myModule->getConfig('surbl')) {
            $options['sources']['surbl'] = preg_split("/[\s]+/", $myModule->getConfig('surbl'));
            if($myModule->getConfig('dnsbl'))
                $options['sources']['dns'] = preg_split("/[\s]+/", $myModule->getConfig('dnsbl'));
            else
                $options['sources']['dnsbl'] = array();
            $options['elements'] = array('title', 'blog_name', 'excerpt');
            $cache_path = XOOPS_TRUST_PATH.'/cache' ;
            if(!(is_dir($cache_path) && is_writable($cache_path))) {
                $trackback->serverErrorWarning($result);	
            }
            $result = $trackback->createSpamCheck('SURBL', $options);
            unset($options);
            if($trackback->isError($result)) {
                $trackback->serverErrorWarning($result);
            }
        }
        $spam = $trackback->checkSpam();
        if ($trackback->isError($spam)) {
            exit(d3blog_responseError($spam->getMessage().' Your trackback smells like spam. If not, please contact the webmaster of this site.', 1));
        }
// debug
//ob_start();$fp=fopen('/tmp/debug.log','a+');var_dump($trackback->_spamChecks);fputs($fp,ob_get_contents());ob_end_clean();
    }

    // save trackback
    if(isset($obj) && is_object($obj)) {
        $obj->setVar('created', time());
    } else {
        $obj =& $tb_handler->create();
    }
//    $obj->assignVars($trackback->_data);
    $obj->setVar('bid', $bid);
    $obj->setVar('direction', 2);
    $obj->setVar('blog_name', $trackback->_data['blog_name']);
    $obj->setVar('url', $trackback->_data['url']);
    $obj->setVar('title', $trackback->_data['title']);
    $obj->setVar('exceprpt', $trackback->_data['excerpt']);
    $obj->setVar('host', $trackback->_data['host']);

    if($myModule->getConfig('trackback_approval')) {
        $obj->setVar('approved', 0);
    } else {
        $obj->setVar('approved', 1);
    }

    if(!$tb_handler->insert($obj, true)) {
        exit(d3blog_responseError('Sorry, server error occurred', 1));
    }

    // send notifications
    $notification_handler =& xoops_gethandler('notification');
    $tags = array(
        'TITLE' => $entry->title(),
        'TRACKBACK_TITLE' => $obj->getVar('title'),
        'BLOGGER_NAME' => $entry->uname(),
        'TRACKBACK_URI' => sprintf('%s/modules/%s/details.php?bid=%d#trackback', XOOPS_URL, $mydirname4show, $bid)
    );

    if($obj->isApproved()) {
        // notify
        $notification_handler->triggerEvent('global', 0, 'trackback', $tags);
        $notification_handler->triggerEvent('entry', $bid, 'trackback', $tags);
        
        // increment trackback count
        $entry_handler->incrementTrackbacks($entry);
    } else {
        // request for approval
        $tags['WAITING_URI'] = sprintf('%s/modules/%s/admin/index.php?page=approval_manager', XOOPS_URL, $mydirname4show);
        require_once dirname(dirname(__FILE__)).'/lib/perm.php';
        $notification_handler->triggerEvent('global', 0, 'tb_received', $tags, myPerm::getUsersByName('blog_editor'));
    }
/*
	// export comment
    if($myModule->getCnfig('dblog_comment_system')) {
    	$com_handler =& $myModule->getHandler('commnet');
    	$comment =& $com_handler->create();
    	$comment->setVar('com_bid', $obj->getVar('bid', 'n'));
    	$comment->setVar('com_tid', $obj->getVar('tid', 'n'));
    	$comment->setVar('com_type', D3BLOG_COM_TYPE_TRACKBACK);
    	$comment->setVar('com_status', $obj->getVar('approved')? D3BLOG_COM_ACTIVE : D3BLOG_COM_PENDING);
    	$comment->setVar('com_title', $obj->getVar('title', 'n'));
    	$text = $obj->getVar('excerpt', 'n');
    	$text .= "\n".'[trackback from]';
    	$text .= "\n".'[url='.$obj->getVar('url', 'n').']'.$obj->getVar('blog_name', 'n').'[/url]';
    	$comment->setVar('com_text', $text);
    	$comment->setVar('com_created', $obj->getVar('created', 'n'));
    	$comment->setVar('com_modified', $obj->getVar('created', 'n'));
    	$comment->setVar('user_id', 0);
    	$comment->setVar('user_name', $obj->getVar('blog_name', 'n'));
    	$comment->setVar('user_url', $obj->getVar('url', 'n'));
    	$comment->setVar('user_host', $obj->getVar('host', 'n'));
    	$comment->cleanVars();
    	if(!empty($comment->_errors)) {
    		exit( d3blog_responseError('Sorry, server error occurred', 1));
    	}
    	if(!$com_handler->insert($comment)) {
       		exit( d3blog_responseError('Sorry, server error occurred', 1));
    	}

    	$comment->setVar('com_rootid', $comment->getVar('com_id'));
    	$comment->setVar('com_pid', 0);
    	if($comment_handler->insert($comment)) {
        	exit( d3blog_responseError('Sorry, server error occurred', 1));
    	}
    }
*/
    // respond back success
    exit(d3blog_responseSuccess());
    break;
}
?>